<template>
  <div class="detail">
    <!-- 主图轮播 -->
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="image in detail.photo" :key="image.id">
        <img v-lazy="image.url" :style="{width: '100%', height: '100%'}" />
      </van-swipe-item>
    </van-swipe>

    <h3>{{ detail.title }}</h3>

    <div>
      <span>{{ detail.price }}</span>
    </div>

    <van-divider>商品图文详情</van-divider>
    <img
      v-for="image in detail.descContentList"
      :key="image.id"
      v-lazy="image.url"
      alt=""
      style="width: 100%; vertical-align: middle;"
    >

    <!-- 商品导航 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" />
      <van-goods-action-icon
        icon="cart-o"
        text="购物车"
        :badge="totalAmount"
        @click="$router.push('/cart')"
      />
      <van-goods-action-icon icon="shop-o" text="店铺" />
      <van-goods-action-button type="warning" text="加入购物车" @click="handleAddToCart" />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { getDetail } from '../../api/detail'
export default {
  name: 'Detail',
  data() {
    return {
      detail: {}, // 商品详情
    }
  },
  computed: {
    totalAmount() {
      const amounts = this.$store.getters['shoppingCart/totalAmount']
      return amounts >= 100 ? '99+' : (amounts > 0 ? amounts : '')
    },
  },
  created() {
    // 商品 id
    const { id } = this.$route.query
    // 查找商品详情数据
    getDetail(id)
      .then(data => {
        console.log('详情：', data)
        this.detail = data.detail
      })
      .catch(error => console.error('异常', error))
  },
  methods: {
    /**
     * 处理加入购物车
     */
    handleAddToCart() {
      const { id, title, price, image } = this.detail
      // 构建当前选购商品对象
      const currentProduct = {
        id,
        title,
        price,
        image,
        amount: 1, // 选购数量
      }
      // 保存到 vuex 的 store 中
      this.$store.commit('shoppingCart/addToCart', currentProduct)
      // 提示
      Toast.success({
        message: '加入购物车',
        duration: 500,
      })
    },
  },
}
</script>

<style lang="less" scoped>
  .detail {
    padding-bottom: 50px;
  }
</style>
